//
//  RssFeedThread.m
//  BaoVn
//
//  Created by Phuong Le on 11/27/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "RssFeedThread.h"
#import "SyncHttpRequest.h"
#import "SyncMutableArray.h"
#import "WebsiteInfo.h"

@implementation RssFeedThread

- (instancetype)initWithWebsites:(SyncMutableArray *)websites
{
    if (self = [super init])
    {
        _websites = websites;
    }
    
    return self;
}

- (void)start
{
    if (_websites == nil)
    {
        NSLog(@"No websites. Cannot start RssFeedThread");
        
        return;
    }
    
    [super start];
}

- (void)loop
{
    if (_thread)
    {
        return;
    }
 
    _thread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(_thread, ^{
        while (_status != ThreadStop)
        {
            //
            if (_status == ThreadPause)
            {
                NSLog(@"RssFeedThread is pausing");
                [NSThread sleepForTimeInterval:1.0f];

                continue;
            }

            //
            NSLog(@"RssFeedThread is running");
            
            NSUInteger count = [_websites count];
            
            if (count == 0)
            {
                NSLog(@"No websites to feed");
                [NSThread sleepForTimeInterval:1.0f];
                
                continue;
            }
            
            for (NSUInteger i = 0; i < count; i ++)
            {
                WebsiteInfo *websiteInfo = [_websites objectAtIndex:i];
                if (websiteInfo == nil)
                {
                    continue;
                }
                
                NSURL *url = [NSURL URLWithString:websiteInfo.rss];
                
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
                
                [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
                [request setHTTPMethod:@"GET"];
                
                __block NSData *_data = nil;
                [SyncHttpRequest connectionWithRequest:request callback:^(NSData *data)
                 {
                     _data = data;
                 }];
                
                if (_data != nil)
                {
                    NSString *xml = [[NSString alloc] initWithBytes:[_data bytes]
                                                             length:[_data length]
                                                           encoding:NSUTF8StringEncoding];
                    if ([xml hasPrefix:@"<?xml"] == NO)
                    {
                        continue;
                    }
                    
                    NSLog(@"Rss feed: %@", xml);
                }
            }
            
            //
            NSLog(@"Restart to feed after x seconds");
            [NSThread sleepForTimeInterval:60.0f];
        }
    });
}

@end
